﻿var userInfo = {};
var extend = null;
(function (factory) {
    if (typeof define === 'function' && define.amd) {
        define(['jquery'], factory);
    } else if (typeof exports === 'object') {
        factory(require('jquery'));
    } else {
        factory(jQuery);
    }
} (function ($) {
    var pluses = /\+/g;
    function encode(s) {
        return config.raw ? s : encodeURIComponent(s);
    }
    function decode(s) {
        return config.raw ? s : decodeURIComponent(s);
    }
    function stringifyCookieValue(value) {
        return encode(config.json ? JSON.stringify(value) : String(value));
    }
    function parseCookieValue(s) {
        if (s.indexOf('"') === 0) {
            s = s.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\');
        }
        try {
            s = decodeURIComponent(s.replace(pluses, ' '));
            return config.json ? JSON.parse(s) : s;
        } catch (e) { }
    }
    function read(s, converter) {
        var value = config.raw ? s : parseCookieValue(s);
        return $.isFunction(converter) ? converter(value) : value;
    }
    var config = $.cookie = function (key, value, options) {
        if (value !== undefined && !$.isFunction(value)) {
            options = $.extend({},
            config.defaults, options);

            if (typeof options.expires === 'number') {
                var days = options.expires,
                t = options.expires = new Date();
                t.setTime(+t + days * 86400 + 5);
            }
            return (document.cookie = [encode(key), '=', stringifyCookieValue(value), options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '', options.domain ? '; domain=' + options.domain : '', options.secure ? '; secure' : ''].join(''));
        }
        var result = key ? undefined : {};
        var cookies = document.cookie ? document.cookie.split('; ') : [];
        for (var i = 0,
        l = cookies.length; i < l; i++) {
            var parts = cookies[i].split('=');
            var name = decode(parts.shift());
            var cookie = parts.join('=');
            if (key && key === name) {
                result = read(cookie, value);
                break;
            }
            if (!key && (cookie = read(cookie)) !== undefined) {
                result[name] = cookie;
            }
        }
        return result;
    };
    config.defaults = {};
    $.removeCookie = function (key, options) {
        if ($.cookie(key) === undefined) {
            return false;
        }
        $.cookie(key, '', $.extend({},
        options, {
            expires: -1
        }));
        return !$.cookie(key);
    };
}))
$(function () {
    $.removeCookie('userinfo');
    var u = $.cookie('userinfo');
    if (u == undefined) {
        $.getJSON('/index.php?a=ajax&type=getUserInfo',
        function (e) {
            console.log('getuser');
            if (e.success) {
                var ui = e.data;
                userInfo = ui;
                var expiresDate = new Date();
                expiresDate.setTime(expiresDate.getTime() + (600 * 1000));
                $.cookie("userinfo", JSON.stringify(ui), {
                    expires: expiresDate
                });
                setUser();
                if (extend != null) extend();
            }
        });
    } else {
        console.log('exists user');
        userInfo = $.parseJSON(u);
        setUser();
        if (extend != null) extend();
    }
    $("body").append('<script src="/static/home/js/jiapu/layer.js" type="text/javascript"></sc'+'ript>').
    append('<link href="/static/home/css/jiapu/layer.css" type="text/css" rel="stylesheet"/>').
    append('<link href="/static/home/css/jiapu/layer.ext.css" type="text/css" rel="stylesheet"/>');
});
var loginOut = function () {
    $.getJSON('/index.php?a=member&type=ajaxlogout', function (e) {
        if (e.success) {
            $.removeCookie('userinfo');
            window.location = "/";
        }
        else {
            alert(e.message);
        }
    });
};

extend = function () {
    new comment(userInfo, commentList).buildHtml()
};
var commentList = {};
var comment = function (user, commentList) {
    var user, list, buildHtml;
    this.user = user;
    this.list = commentList;
    this.buildHtml = function () {
        $(".comment-text,.comment-submit").removeClass("disabled");
        $(".comment-text.comment-avatar").attr('src',user.avatar);// css("background", " url(" + user.avatar + ") 50% 50% / 80% no-repeat rgb(241, 241, 241)");
        $(".add-comment.username").text(user.nickname);
        if(user.id)
        {
            $(".comment-login").attr('href','/user/'+user.id);
        }
        $(".comment-nickname").text(user.nickname);
        $(".comment-text").attr("placeholder", "你怎么看...");
        $(".comment-text-div").after("<div class='blockel' style='color:#999;font-size:12px; padding-top:10px;'>请回复有价值的信息，无意义的评论将很快删除，账号将禁止发言</div>");
        if(typeof(pConfig)== "undefined")
        {
            return ;
        }
        $.getJSON("/index.php?a=ajax&type=getPageInfo", {
            datatype: typeof(pConfig)!= 'undefined'? pConfig.type:"",
            dataid: typeof(pConfig)!= 'undefined'? pConfig.id:"",
        },
        function (r) {
            if (r.favorite) {
                $(".tofavorite i").addClass("hover")
            }
            if(r.hits)
            {
                $(".hitcnt").text(r.hits);
            }
            if(r.followed)
            {
                $('.btn-follow').addClass('followed').addClass('W_btn_a_disable').removeClass('W_btn_c').text("已关注");
            }
            var e = r.comments;
            if (!e) {
                return
            }
            for (var m = 0; m < e.length; m++) {
                var comment = e[m];
                if ($(".comment-item[dataid=" + comment.id + "]").length > 0) {
                    continue
                }
                var user = comment.user;
                if (user == undefined || user.avatar == "") {
                    continue
                }
                var parentid = comment.parentid;
                var str =htmlCommentItem(comment,user);
                var parent = $(".comment-item[dataid=" + parentid + "]");
                if (parent.length == 0) {
                    $(".comment-items").append(str);
                } else {
                    parent.append(str);
                }
            }
            $(".comment-reply[userid=" + userInfo.id + "]").hide();
            commentReply();
        })
    }
};
var commentReply=function(){
        $(".comment-reply").click(function () {
        console.log('huifu');
        commmentid = $(this).attr("data-id");
        $(".blockel").html('<div class="replytip"><span class="parent-name">回复: ' + $(this).attr("nickname") + '</span><span class="close">×</span></div>请回复有价值的信息，无意义的评论将很快删除，账号将禁止发言');
        window.location.href = window.location.href + "#comment-black";
        $(".comment-text").focus();
        $(".replytip .close").click(function () {
            $(this).closest("div").remove();
            commmentid = 0
        })
    });
};
$(function () {
    $(".btn-follow").click(function(){
        var id =$(this).attr('dataid');
        var fed = $(this).hasClass('followed');
        var btn= $(this);
        if(userInfo.id>0)
        {
            $.getJSON('/index.php?a=ajax&type=follow',{'userid':id , fed:fed?0:1},function(r){
                if(r.success)
                {
                    if(fed){
                        btn.removeClass('followed');
                        btn.removeClass('W_btn_a_disable').addClass('W_btn_c').html('<em class="fwb fs16 m-r5">+</em>关注');
                    }
                    else
                    {
                        btn.addClass('followed');
                        btn.addClass('W_btn_a_disable').removeClass('W_btn_c').text("已关注");
                    }
                }
            });
        }
    });
    $(".tofavorite").click(function () {
        console.log('fav');
        var btn = $(this).find("i");
        if (userInfo.id > 0) {
            $.getJSON("/index.php?a=ajax&type=favorite", {
                datatype: typeof(pConfig)!= 'undefined'? pConfig.type:"",
                dataid: typeof(pConfig)!= 'undefined'? pConfig.id:"",
            },
            function (r) {
                if (r.success) {
                    if (btn.hasClass("hover")) {
                        btn.removeClass("hover");
                    } else {
                        btn.addClass("hover");
                        var b=$(".favoritecnt");
                        if(b.length>0)
                        {
                            var n =parseInt( b.text());
                            if(!isNaN(n))
                            {
                                b.text(n+1);
                            }
                        }
                    }
                }
            })
        } else {
            window.location.href = "/index.php?a=member&type=login&gourl=" + window.location.href
        }
    });
    commentReply();
    $(".comment-text").focusin(function () {
        $(".input-module .error").remove()
    });
    $(".comment-submit").unbind("click").click(function () {
        console.log('提交评论');
        if ($(this).hasClass("disabled")) {
            return;
        }
        var str = $(".comment-text").val();
        $(".comment .error").remove();
        if (str == "") {
            $(".blockel").after('<p class="msg error">请输入评论内容</p>');
            return false
        }
        $(this).addClass("disabled");
        $.getJSON("/index.php?a=ajax&type=addComment", {
            datatype: typeof(pConfig)!= 'undefined'? pConfig.type:"",
            dataid: typeof(pConfig)!= 'undefined'? pConfig.id:"",
            datauserid:typeof(pConfig)!= 'undefined'? pConfig.userid:"",
            commentid: commentid,
            content: str
        },
        function (e) {
            $(".comment-submit").removeClass("disabled");
            if (e.success) {
                var data = e.data;
                if(commentid>0)
                {
                    var parent = $(".comment-item[dataid=" + commentid + "]").append(str);
                   
                }
                else
                {
                  
                    $(".comment-items").html( htmlCommentItem(data,userInfo) + $(".comment-items").html())
                }
               $(".comment-reply[userid=" + userInfo.id + "]").hide()
            } else {
                $(".blockel").after('<p class="msg error">' + e.message + "</p>")
            }
        })
    });
}); 
var htmlCommentItem=function(comment,user)
{
    var str = '<li class="line-b2 comment-item" dataid="'+comment.id+'">';
    str+='<a class="ith_img" href="/user/'+user.id+'/" style="background-image:url('+(user.avatar?user.avatar:'/assets/attch/logo-100.png')+');"></a>'+
    '<div class="d-info">'+
        '<a href="/user/'+user.id+'/"><span class="c-cbb163">'+user.nickname+'</span><span class="c-999999"> • '+comment.addtimestr+'</span></a>'+
        '<div class="LH20 oh m-t5 p-r25">'+comment.content+'</div>'+
        '<a href="javascript:;" class="i_btn c-cbb163 comment-reply " nickname="'+user.avatar+'" userid='+user.id+' dataid="'+comment.id+'">回复</a>'+
    '</div></li>';
    return str;
}
var setUser = function () {
    if (userInfo.id > 0) {
         $(".privilege-logined-8").each(function () {
            var el = $(this);
            var href = el.attr('orgHref');

            if (href) {
                el.attr('href', href);
                //el.attr("href", "/member/login/");
            }   
            var html = el.attr("innerHtml");
            if(html!="undefined")
            {  
                el.unbind("click",elemntClickGoLogin);
                el.html(html);
            }
            
        });
        var str = "";
        console.log('set uesr');
        var avatar = userInfo.avatar, nickname = userInfo.nickname;
        var bm = userInfo.branchmember;
        str += '<div class="userLogin m-l10"><a href="/member/"><span class="ith_img usernane_img36 ir" style="overflow:visible;">';
        str += '<img src="' + (avatar != "" ? avatar : "/assets/attch/logo-100.png") + '" />';
        if (bm) {
            if (bm.vip) str += '<i class="u2 b-daa900 fs11 c-FFFFFF p-lr5 ia" style="bottom:-3px; right:-10px;">VIP</i>';
            if (bm.ming) str += '<i class="u2 b-4488dd fs11 c-FFFFFF p-lr5 ia" style="bottom:-3px; right:-10px;">名</i>';
            if (bm.yi) str += '<i class="u2 b-c5619e fs11 c-FFFFFF p-lr5 ia" style="bottom:-3px; right:-10px;">艺</i>';
            if (bm.ci) str += '<i class="u2 b-4eb66e fs11 c-FFFFFF p-lr5 ia" style="bottom:-3px; right:-10px;">慈</i>';
            if (bm.li) str += '<i class="u2 b-d66b3c fs11 c-FFFFFF p-lr5 ia" style="bottom:-3px; right:-10px;">理</i>';
            if (bm.wen) str += '<i class="u2 b-905bc7 fs11 c-FFFFFF p-lr5 ia" style="bottom:-3px; right:-10px;">文</i>';
        }
        str += '</span></a><div class="urLbox fs13"><div class="iiZx"><i></i></div><div class="itMian"><div class="line-b p-tb15"><span class="ith_img usernane_img36 ir" style="overflow:visible; display:inline-block;">';
        str += '<img src="' + (avatar != "" ? avatar : "/assets/attch/logo-100.png") + '" />';
        if (bm) {
            if (bm.vip) str += '<i class="u2 b-daa900 fs11 c-FFFFFF p-lr5 ia" style="bottom:-3px; right:-10px;">VIP</i>';
            if (bm.ming) str += '<i class="u2 b-4488dd fs11 c-FFFFFF p-lr5 ia" style="bottom:-3px; right:-10px;">名</i>';
            if (bm.yi) str += '<i class="u2 b-c5619e fs11 c-FFFFFF p-lr5 ia" style="bottom:-3px; right:-10px;">艺</i>';
            if (bm.ci) str += '<i class="u2 b-4eb66e fs11 c-FFFFFF p-lr5 ia" style="bottom:-3px; right:-10px;">慈</i>';
            if (bm.li) str += '<i class="u2 b-d66b3c fs11 c-FFFFFF p-lr5 ia" style="bottom:-3px; right:-10px;">理</i>';
            if (bm.wen) str += '<i class="u2 b-905bc7 fs11 c-FFFFFF p-lr5 ia" style="bottom:-3px; right:-10px;">文</i>';
        }
        str += '</span><span class="fs14 p-l15 p-l20">' + nickname + '</span></div>';
        str += '<a href="/user/' + userInfo.id + '/">我的主页</a><a href="/member/favorite/">我的收藏</a><a href="/member/user/">账号设置</a><a href="javascript:loginOut()">退出</a>';
        str += '</div></div></div><a class="itdiv myMessage" href="/member/message/" ><i class="ico-20 c2015-ico"></i><span>消息</span></a>';
        str += ' <a class="itdiv" href="http://sighttp.qq.com/msgrd?v=&uin='+siteConfig.qqkefu+'&site='+siteConfig.sitename+'&menu=yes" target="_blank"><i class="ico-20 c2006-ico"></i><span>客服</span></a> ';
        $(".userinfo-header").html(str);
    }
};
var feedback = function(){
	if(userInfo.id == undefined || userInfo.id<=0){
		alert("用户没有登录请先登录");
		location = "/member/login/";
		return;
	}else{
		layer.open({
	      type: 2,
	      title: null,
	      shadeClose: true,
	      closeBtn:0,
	      shade: 0.4,
	      maxmin: false, //开启最大化最小化按钮
	      area: ['520px', '620px'],
	      content: '/index.php?a=events&feedType=jiucuo&type=feedback&refer='+encodeURIComponent(JSON.stringify(pConfig))
	    });
	}
}
var closeFeedBack = function(){
	layer.closeAll();
}